import React from 'react'

interface IUser { userId?: number, token?: string, isLogin: boolean }
interface IUserAction { login: (user: IUser) => Promise<IUser>, loginOut: () => void }
interface IUserContext extends IUserAction { user: IUser }

let user: IUser = { isLogin: false }
let userStr = localStorage.getItem('currentUser');
if (userStr) {
	user = JSON.parse(userStr);
}
const UserContext = React.createContext<IUserContext>({ user } as any);
class UserProvider extends React.Component<React.Props<any>, IUserContext> {
	constructor(props: any) {
		super(props)
		this.state = { user, login: this.login, loginOut: this.loginOut };
	}
	login = async (newuser: IUser) => {
		user = newuser;
		this.setState({ user })

		return user;
	}
	loginOut = () => {
		localStorage.removeItem('currentUser');
		user = { isLogin: false };
		this.setState({ user })
	}
	componentDidCatch() {
		console.log('error')
	}
	render() {
		let { children } = this.props;
		return (<UserContext.Provider value={this.state}>
			{children}
		</UserContext.Provider>)
	}

}

export default class {
	public static Provider = UserProvider
	public static Consumer = UserContext.Consumer
	public static user = user
}